<template>
  <a-row :gutter="24" class="search-row">
    <x-card>
      <div slot="content" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item
                label="违章单位"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
              >
                <a-tree-select
                  allowClear
                  showSearch
                  style="scroll:true"
                  tree-node-filter-prop="title"
                  v-model="queryParam.OrganizationName"
                  :treeData="QHSEOrganizationTree"
                  v-if="QHSEOrganizationTree.length"
                  @change="handleOrganizationSelectChange"
                  :defaultExpandAll="true"
                  :defaultExpandedKeys="defaultExpandedKeys"
                  :replaceFields="replaceFields"
                  ref="tree"
                  placeholder="请选择违章单位"
                  :title="queryParam.OrganizationName" />
              </a-form-item>
            </a-col>
            <a-col :span="7" >
              <a-form-item
                label="检查时间"
                :labelCol="{ style: 'width:115px' }"
                :wrapperCol="wrapperCol"
              >
                <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange1" :style="{width: '50%'}" v-model="TimeOn"/>
                <a-date-picker style="width: 100%" format="YYYY-MM-DD" @change="onChange2" :style="{width: '50%'}" v-model="TimeEnd"/>
              </a-form-item>
            </a-col>
            <a-col :span="6" style="margin-bottom: 3px;">
              <a-button type="primary" @click="handleClick" :loading="saving">查询</a-button>
              <a-button type="default" @click="exportToExcel" style="margin-left: 8px;">导出</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </x-card>
    <a-row :gutter="48" class="search-row">
      <a-col :span="24">
        <a-divider orientation="left" style="font-weight: bold; margin-bottom: -2px;margin-top: -2px"> 违章统计通报
        </a-divider>
        <a-card style="overflow-y: auto;" :bordered="false">
          <a-row style="width: 100%; height: 400px;">
            <a-progress
              v-if="batchExportLoading"
              :percent="exportProgress"
              status="active"
            />
            <a-col :span="24">
              <a-table
                bordered
                :columns="columns"
                :dataSource="loadData"
                :alert="false"
                :pagination="false"
                :rowKey="(record, index) => index"
              >
              </a-table>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
  </a-row>
</template>
<script>
import { STable, XCard, XDown } from '@/components'
import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
import moment from 'moment'
import { getQHSEStartTableViolationCheckCount, getQHSEGetTableVioCheStatus, getQHSETakeTableViolationCheckCount } from '@/api/modular/system/QHSEVIOReports/QHSEVioTotal'
import { mapGetters } from 'vuex'
import * as XLSX from 'xlsx'
export default {
    components: {
      XDown,
      XCard,
      STable
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        defaultExpandedKeys: [],
        QHSEOrganizationTree: [],
        task: {
          Id: ''
        },
        secondOraName: {
            id: ''
        },
        exportProgress: 0,
        status: '',
        batchExportLoading: false,
        replaceFields: {
          children: 'children',
          title: 'title',
          key: 'workflowId',
          value: 'id',
          parentId: 'parentId'
        },
        queryParam: {
          TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
          TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59'),
          OrganizationName: '川庆钻探',
          OrganizationId: '00'
        },
        TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
        TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
        saving: false,
        // 表头
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '单位名称',
            dataIndex: 'organizationName'
          },
          {
            title: '自查违章（起）',
            dataIndex: 'value1'
          },
          {
            title: '监督查纠（起）',
            dataIndex: 'value2'
          }
        ],
        loadData: [],
        dangerCheckData: []
        }
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    created() {
      this.getQHSEOrganizationTree()
    },
    methods: {
      onChange1(date, dateString) {
        // console.log(dateString, date)
        if (this.queryParam.TimeEnd && dateString) {
          if (dateString > this.queryParam.TimeEnd) {
            this.$message.error('检查开始时间不能晚于结束时间')
            this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeOn = dateString
          }
        } else {
          this.queryParam.TimeOn = dateString
        }
        // console.log('TimeOn1', this.queryParam.TimeOn1)
      },
      onChange2(date, dateString) {
        if (this.queryParam.TimeOn && dateString) {
          if (this.queryParam.TimeOn > dateString) {
            this.$message.error('开始时间不能晚于结束时间')
            this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd1 = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
          }
        } else {
          this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
        }
        // console.log('TimeEnd1', this.queryParam.TimeEnd1)
      },
        // 更改违章单位
        handleOrganizationSelectChange(val, opt, extra) {
          if (extra.triggerNode === undefined) {
            this.queryParam.OrganizationName = null
            this.queryParam.OrganizationId = null
          } else {
            const option = extra.triggerNode._props.title
            this.queryParam.OrganizationName = option
            this.queryParam.OrganizationId = extra.triggerNode._props.value
          }
        },
        // 组织树
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree = res.data
        if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
        })
      },
      exportToExcel() {
          // 设置导出的数据，手动调整字段名称
          const exportData = this.loadData.map((item, index) => ({
              单位名称: item.organizationName,
              自查违章数量: item.value1,
              监督查纠数量: item.value2
          }))
          // 创建工作表和工作簿
          const ws = XLSX.utils.json_to_sheet(exportData)
          const wb = XLSX.utils.book_new()
          XLSX.utils.book_append_sheet(wb, ws, '违章统计通报')
          // 导出 Excel 文件，文件名带当前日期
          XLSX.writeFile(wb, `违章统计通报_${moment().format('YYYYMMDD')}.xlsx`)
      },
      handleClick() {
        if ((!this.TimeOn && !this.TimeEnd) || (this.TimeOn && this.TimeEnd)) {
          // 后端方法
          this.select()
        } else {
          this.$message.warning('请填写完整的查询条件')
        }
      },
      select() {
        // 后端方法
        this.saving = true
        this.batchExportLoading = true
        getQHSEStartTableViolationCheckCount(this.queryParam).then((res) => {
          // console.log('res.taskId', res.taskId)s
          this.task.Id = res.taskId
        })
        this.exportProgress = 0 // 重置进度
        setInterval(() => {
          if (this.exportProgress < 90) { // 进度最高到 90%，剩下的 10% 在下载完成时更新
            this.exportProgress += 10
          }
        }, 500)
           // 每 5 秒轮询状态
        const statusInterval = setInterval(() => {
          getQHSEGetTableVioCheStatus(this.task).then((res) => {
            this.status = res.status
           if (this.status === 'completed') {
             // 清除进度定时器，确保定时器被清除
             clearInterval(statusInterval)
             // 开始执行 getExportToExcel
             getQHSETakeTableViolationCheckCount(this.task).then((res) => {
               this.loadData = res.data.table
               this.exportProgress += 10
               this.batchExportLoading = false
              //  console.log('this.loadData', this.loadData)
             })
             .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
              })
           }
          }).catch(error => {
          console.error('状态获取失败:', error)
          clearInterval(statusInterval) // 出现错误时，也要清除定时器
          // clearInterval(interval)
         })
       }, 5000)
      }
    }
}
</script>

<style lang="less" scoped>
/deep/.ant-table-tbody tr:last-child
 {
  background-color:#f5f5f5d6;
 }

</style>
